package gateway

import (
	"context"
	"fmt"
	"net/http"
	"sync"
	"time"
)

// 中间件链
type Middleware func(next Service) Service

// logProxy 日志代理
type logProxy struct {
	next   Service
	logger func(string)
}

// Name 日志代理名称
func (lp *logProxy) Name() string {
	return lp.next.Name()
}

// HandleRequest 处理请求
func (lp *logProxy) HandleRequest(ctx *context.Context, req *http.Request) (*http.Response, error) {
	start := time.Now()
	resp, err := lp.next.HandleRequest(ctx, req)
	duration := time.Since(start)
	lp.logger(
		"[PROXY] " + req.Method + " " + req.URL.Path +
			" | Service: " + lp.Name() +
			" | Duration: " + duration.String() +
			" | Status: " + http.StatusText(resp.StatusCode),
	)
	return resp, err
}

// 日志中间件
func LogMiddleware(logger func(string)) Middleware {
	return func(next Service) Service {
		return &logProxy{
			next:   next,
			logger: logger,
		}
	}
}

// 限流代理
type rateLimitProxy struct {
	next         Service
	limit        int
	interval     time.Duration
	requestCount int
	lastReset    time.Time
	mu           sync.Mutex
}

// Name 限流代理名称
func (rlp *rateLimitProxy) Name() string {
	return rlp.next.Name()
}

// HandleRequest 处理请求
func (rlp *rateLimitProxy) HandleRequest(ctx *context.Context, req *http.Request) (*http.Response, error) {
	rlp.mu.Lock()
	defer rlp.mu.Unlock()

	fmt.Println("rateLimitProxy start......")

	// 重置计数器
	if time.Since(rlp.lastReset) > rlp.interval {
		rlp.requestCount = 0
		rlp.lastReset = time.Now()
	}

	// 检查是否超限
	if rlp.requestCount >= rlp.limit {
		resp := &http.Response{
			StatusCode: http.StatusTooManyRequests,
			Body:       http.NoBody,
		}
		return resp, nil
	}

	rlp.requestCount++
	return rlp.next.HandleRequest(ctx, req)
}

// 限流中间件
func RateLimitMiddleware(limit int, interval time.Duration) Middleware {
	return func(next Service) Service {
		return &rateLimitProxy{
			next:      next,
			limit:     limit,
			interval:  interval,
			lastReset: time.Now(),
			mu:        sync.Mutex{},
		}
	}
}
